package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.example.myapplication.utils.QZXTools;
import com.sanstar.baiduFacePay.BaiduFacePay;
import com.sanstar.baiduFacePay.BaiduFacePayCode;
import com.sanstar.baiduFacePay.callback.IBaiduFaceCB;

import java.lang.ref.WeakReference;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author: Administrator
 * @date: 2023/7/5
 */

public class CameraTestActivity extends Activity {
    final private String TAG = CameraTestActivity.class.getSimpleName();
    private TextView textView1;
    private TextView textView2;

    SurfaceView mSurface;

    MyHandler mHandler;

    HashMap<String, Object> map = new HashMap<>();

    private class MyHandler extends Handler {

        private WeakReference<Activity> activityWeakReference;

        public MyHandler(Activity activity) {
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Activity activity = activityWeakReference.get();
            Log.d(TAG, "msg = " + msg.what);
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        BaiduFacePay.getInstance().setCameraPreview(mSurface, map, new IBaiduFaceCB() {
                            @Override
                            public void response(Map map) {
                                mHandler.sendEmptyMessage(2);
                            }
                        });
                        break;
                    case 2:
                        BaiduFacePay.getInstance().startVerify(map, new IBaiduFaceCB() {
                            @Override
                            public void response(Map map) {
                                String msg = (String) map.get("return_msg");
                                int code = (int) map.get("return_code");
                                Log.d(TAG, "start verity msg = " + msg + ", code = " + code);
                                if(code != -10011 && code != -10012) {
                                    Float rgbScore = (Float) map.get("return_rgbLivenessScore");
                                    Log.d(TAG, "rgbScore = " + rgbScore);
                                    Log.d(TAG, "imagePath = " + map.get("return_imagePath"));
                                }
                                if(msg.equals("SUCC")) {
                                    if(code == 10000) {
                                        runOnUiThread(() -> textView1.setText("相机打开成功"));
                                        Log.d(TAG, "相机打开成功");
                                    } else {
                                        String user_id = (String) map.get("return_user_info_id");
                                        String name = (String) map.get("return_user_info_name");
                                        runOnUiThread(() -> {
                                            textView1.setText("识别成功");
                                            textView2.setText("用户" + user_id + ", 姓名:" + name);
                                        });
                                        Log.d(TAG, "verity user_id = " + user_id + ", name = " + name);
                                        mHandler.sendEmptyMessage(3);
                                    }
                                } else {
                                    runOnUiThread(() -> textView1.setText(msg));
                                }
                            }
                        });
                        break;
                    case 3:
                        BaiduFacePay.getInstance().removeCameraPreview(mSurface, map, new IBaiduFaceCB() {
                            @Override
                            public void response(Map map) {
                                String msg = (String) map.get("return_msg");
                                int code = (int) map.get("return_code");
                                runOnUiThread(() -> textView1.setText(msg));
                                Log.d(TAG, "remove preview msg = " + msg + ", code = " + code);
                                finish();
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        textView1 = findViewById(R.id.Text_tip1);
        textView2 = findViewById(R.id.Text_tip2);
        mSurface = findViewById(R.id.surface_rgb_view);

        mHandler = new MyHandler(this);

//        map.put("pictureURL", "sdcard/123.jpg");
//        BaiduFacePay.getInstance().getFaceFeature(map, new IBaiduFaceCB() {
//            @Override
//            public void response(Map map) {
//                String msg = (String) map.get("return_msg");
//                int code = (int) map.get("return_code");
//                byte[] feature = (byte[]) map.get("feature");
//                Log.d(TAG, "get feature msg = " + msg + ", code = " + code);
//                Log.d(TAG, "feature = " + Base64.getEncoder().encodeToString(feature));
//            }
//        });


        BaiduFacePay.getInstance().setCameraPreview(mSurface, map, new IBaiduFaceCB() {
            @Override
            public void response(Map map) {
                String msg = (String) map.get("return_msg");
                int code = (int) map.get("return_code");
                if(msg.equals("SUCC")) {
                    mHandler.sendEmptyMessage(2);
                }
            }
        });

        findViewById(R.id.init_verity).setOnClickListener((view) ->{
            BaiduFacePay.getInstance().initBaiduFace(this, map, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    }
                    runOnUiThread(() -> textView1.setText("初始化" + msg + ", code = " + code));
                    Log.d(TAG, "init msg = " + msg + ", code = " + code);
                }
            });
        });


        findViewById(R.id.preload_env).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().preloadSdkEnv(map, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    }
                    runOnUiThread(() -> textView1.setText("环境加载" + msg + ", code = " + code));
                    Log.d(TAG, "preload msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.upload_user).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().manualUpdateFaceData(map, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    }
                    runOnUiThread(() -> textView1.setText("内存加载" + msg + ", code = " + code));
                    Log.d(TAG, "upload user msg = " + msg + ", code = " + code + ", user num = " + String.valueOf(info.get("return_user_num")));
                }
            });
        });

        List<Map<String, Object>> mapInfo = new LinkedList<>();

        String str ="nhTxkKxmgGtNXwyaDmQQHNxnEoLevkMG1Kqc96PCrw6eZ3wx3JhXNQSqFDi/Vxg8W0Ob39a2ltvG61go9UCRLBxG2lDbG8hUQJDT2LJvJV2sH33B4/zvO21CdcgL8HAzroxP8Izk2IsOU7P4uDpb/PvxmuAs1pPkQ3246HO8wWxKeNqRVqgjlKVxZhjuZJKczFbrAW1RUwX+pJuIUrw283b6Gk9Pbbi1458gx6J/e71UE0ag68CGpFZRrajN7sgs+CWjUcaVtlSsNwdYacg9XDfkosAJnO9E8ZxEt2S7RjObouhwK+bLdIy1Xni81al9LnqW4AYeEmZACLxpWmDe7C8L/+/XTbjrgouZGGuff5ys3saByRCHe7DYz4jKBvuMU2LzsDbNSrQfb+e4fzWAwxwUEyBjLDmkMtuKqD+dySx9uPFQOoWB1DN6yCeLmPBcO+Z8QUy6l8RksL834rjZzJLl+3ODW8p1Qv/R+ED6QPyxNnthCY355JHuTOim6p3s4H38kHGOZBXxHZgYksvEHTSQt4C82G+Ehq9xdycPGPM63/mzJo49y7AQq7meSoC8dsCUIsQ+FaR2aUlXL9m9rPDhda9Yu+ZVf0wJWHJB2tyLXW3AIuwXRMcgfbdYYBRMeItADxfGT3SF39x4KL/xfbjA92D7eXtkFgRt6BVsBew=";

        Map map1 = new HashMap() {{
            put("userID", "002");
            put("userName", "liuh");
            put("picName", "liuh");
            put("userInfo", "staff");
            put("faceToken", str);
            put("feature", Base64.getDecoder().decode(str));
        }};
        mapInfo.add(map1);


        String str2 = "9vy1EjYPZpfNd3+YO5eGnH0mnn+A3bh7dWWwiNJ3iYziZv4www0yNDpeqDhbWw68fUu731dLOaR13RSpISBYLP7hzi+OTjlVFlL82JnHI1xSlWDAaWkhRPtOkEiT+SvO1MADcF9U1fTMZjN489Re/moEwh/CiQPmMVuZaGnrouweaSwQhMsba/zjVRjubTpjmC+MAfW/KXuQizEIjX7wDABHjTCQHa02m43tuJZ6Qz1sehdfYI1RJd0iBdfYiP0tRR/g0GylIVW+mwjZSoNpI+HM5UCzg2BFRI0FSd4+18xbRMjxaIoU9LxxEnnbFFj816fh4OSzSuRrWGEXRPZDk0qf1ZAq1dAV88NZmMEZcx0gN/MALmgYhOOsNIjr3PYMSDswMTHaXDSBg0q5oJsbPJHAFSBabcGlLIpbKFVLESyNAo2vNP3eq44tVdkSZdfdoMPqv2kT2sSLyL/IIg1gzIAf43Db7xz1kQ4O+WTMR3z3PkDgpu6UZCyTFmmEpp5t2jzWkEQRqBWkK0aZM0RjnEaLjoHvwt6EJ3V899xHm42ZpLIxp8EYtPoenzg8SZg8IcCvIb7yBKVOk8Uo4aylLEXUSS9wInKrXJBJWLKPttzfwZDCNQLcxO/9eLfxZxvNO3Dv8LP7pnVuL9P46DFX/KUBueHWjobkKkzm6Xc4U5M=";
        Map map2 = new HashMap() {{
            put("userID", "sanstar2");
            put("userName", "hany");
            put("picName", "hany");
            put("userInfo", "staff");
            put("faceToken", str2);
            put("feature", Base64.getDecoder().decode(str2));
        }};
        mapInfo.add(map2);

        String str3 = "sEl7ELwmyhYRJPEYKhMvnLJpDAAefScEdhsTCgL6gIzI+26xPIa/NN0mqceRSDM8F+2LIFd1ByZxJC0oDYUeLP0vA9GCOYRU9dgjWGxIK9i8azLA5C74O7JUl7eDtktMIPfdD+rH6fSHu394zbzQfMDe+mDp6bOblLHOF+/LmWzTR+KQJCiQlpAttBjgEX6duOTngdJVZgQo/1aIEqdgjBhEzLCwZcQ0RGrLuG+gCzyzunegcRTypDxfQSjOiwyta+LDUVGDblXByCxYiNZEXHvdXUHGJebGkx9HyWJzOkyroJHy0jM2dLRNR3mEMcd9NQuS4PybyGSKn+bpqkLrbJOc9RBAdqHrcIByGK2TyZwayKUAJWnLBG7tmQiYv3uMPPCZT+QEnUtqDz24JDPTvKUtbCH2kYPblLTKqA266qwjuM5QYphR1uX57FiaJLbcvNDHwEkOY0SkDZ7I7kuQzBotjXBuIaSLyTGWeRHZR/w+yDxhdW3BZCUrdWhNx1Hs48JJECSRoJQ4QbYZT/6cHdHZN39TuOKEmtEc9yLD8Qwxomcw9EsPy4LGjji4Ar09tNcA30oGFFs568Cokz/DrbrU6lCYo73QS5X82BcK9908j81AahzQxl+DvcjiPmZM3LCN8FpfPHRwOlr4DTVgfSxOUOG6TthkMutRF2CJyuw=";
        Map map3 = new HashMap() {{
            put("userID", "sanstar3");
            put("userName", "liuj");
            put("picName", "liuj");
            put("userInfo", "staff");
            put("faceToken", str3);
            put("feature", Base64.getDecoder().decode(str3));
        }};
        mapInfo.add(map3);

        String str4 = "jqGTkEdnDhXZdJ9n8rNMHLZ5rIFrnNoE6ussiEooWgzww/ow9mSES1mVLbhgUci8EJ0coNjvKqSPKeSoBD5brD/SIdF0BFXVXHxyWe3Cq1yDrHJAXGj3O5N2yEhgH7nMhaaH8HrZS/d0LuZ46Db2/GTmB2DBR2BkQgyraY5r9WgUCviQtWnXFHuYOpqxpxdjn6vrAFpZrwQq0+6IiuX9DDE5zTHxuRZLERYDuEfao72psQygbnLKpZm7NKhq1RyuF9+80bI2hFaN0fZYkIPwXBxzdsFVVkHFAlbFyPnUNExeEM5w+//BdCTgu/lt50l86kycYNQQT5tbmGOXkjqQbMc2hO8FdSsUWxEvmBwCx52YBQMB9gcthUZq5AibZDiMHIRQMEphlDSGiU44uy2SQ1OjRaHL3P+kjOUYKO/jmKxn/LbQbnnD1RU+MlmtPvTdyDvmwLN8PER7tuq35PLrTH7a3XBztyP0Bm/n+VSDJP3ETYbggYnTG44TnWh7gLHsP1R+ECo+xRQGOQBnevLcHEA7TwDPl0QEID2hCO8kho8kBq4xh7/ENc7QfTigZw3DpRcBoAHuW6RSi38osr0/LcroetAcyxHVqv4dWOqMTl0Uh9lAWuj1xebQW8jSE2UzNw3I8E5YAXYPbrH5gWvkfKIYMuCuUwJkv5DMaaofcZM=";
        Map map4 = new HashMap() {{
            put("userID", "sanstar4");
            put("userName", "yingzt");
            put("picName", "yingzt");
            put("userInfo", "staff");
            put("faceToken", str4);
            put("feature", Base64.getDecoder().decode(str4));
        }};
        mapInfo.add(map4);

        String str5 = "u4E6kFkdPBRXncBn0Pq3nWTGNoC+QxMEM8YcCTM2c4y2KbSwcXSztCUJBThmueI81o62odCgKqREJm2rkEADLJW4aVH0AWlUGbY9W9BwzFx583rAxnrfRpsgYMhatepMHw9HcCpf5ou6OQV40aWyfN6PRGF4kfhk52i56ODJbO54fCuRcJRVlOLRiRgoL2JjZ1N/AEDFqoQ7ye+I+najjCQZZc9VPAo0QRXWOH4orDyLxtagTOIaJRTlrSj/SAesPGLl0P23MysTKoTY3iM+XiPk8sKAfNZF6dF7N03HjM5IxAzx7EUPdP0zQwedR7D87+r0YVAu0ZsLxXtoCwxVE451WhEyWTOUd70MGKSzJJzMxzUBK18QBJ4ziAiTEywND05+scbuqcuU/CA61T5nPLrkC6DSSu6k6FwVqPXzMyxczkRRKAgY1Fu0VFj6XWFcgOnuv2vsREXGtR3JWtSzTPsvK3C4dML1uXSIB6xR4PyncpZgFb6RZMmlkegPoB/sNne/kNdiLhSr7cwavmQYnHVD2wA3kxX7Hm/4CclpCQzEzlYxlDkHtBbfmDhGAtw9Ex2OookeiiQukhJX+H/drE5zaND9/uPUHimGWcAIa1zlIRZAZ0EwRIsgNzdyul8zQjoOj4DlMHRO2nn4RJue/EUJyOCC6wFkDNDB6Egt7ew=";
        Map map5 = new HashMap() {{
            put("userID", "sanstar5");
            put("userName", "wenff");
            put("picName", "wenff");
            put("userInfo", "staff");
            put("faceToken", str5);
            put("feature", Base64.getDecoder().decode(str5));
        }};
        mapInfo.add(map5);




        findViewById(R.id.insert_user).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().insertFaceDatas(mapInfo, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        Log.d(TAG, "insert user msg = " + msg + ", code = " + code);
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    } else {
                        runOnUiThread(() -> {
                            if(code == 10006) {
                                Log.d(TAG, "用户插入成功 msg = " + msg + ", code = " + code + ", 人数= "+info.get("return_user_num"));
                            }
                            if(code == BaiduFacePayCode.Face_Result_Insert_User_Succ) {
                                textView1.setText("用户插入" + msg + ", 插入人数:" + info.get("return_insert_user_num"));
                                Log.d(TAG, "insert user msg = " + msg + ", code = " + code + ", num = " + info.get("return_insert_user_num"));
                            } else {
                                textView2.setText("当前数据库共有人数:" + info.get("return_user_num"));
                            }
                        });

                    }
                }
            });
        });

        findViewById(R.id.update_user).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().updateSingleFaceDatas(map1, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    }
                    runOnUiThread(() -> {
                        textView1.setText(map1.get("userName") + "用户更新" + msg);
                        textView2.setText("当前数据库共有人数：" + info.get("return_user_num"));
                    });
                    Log.d(TAG, "update user msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.set_previrew).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().setCameraPreview(mSurface, map, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    runOnUiThread(() -> textView1.setText("预览设置" + msg));
                    Log.d(TAG, "set preview msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.remove_previrew).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().removeCameraPreview(mSurface, map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    runOnUiThread(() -> textView1.setText(msg));
                    Log.d(TAG, "remove preview msg = " + msg + ", code = " + code);
                }
            });

        });

        findViewById(R.id.start_verity).setOnClickListener((view) -> {
            runOnUiThread(() -> {
                textView1.setText("");
                textView2.setText("");
            });
            BaiduFacePay.getInstance().startVerify(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    Log.d(TAG, "start verity msg = " + msg + ", code = " + code);
                    if(code != -10011 && code != -10012) {
                        Float rgbScore = (Float) map.get("return_rgbLivenessScore");
                        Log.d(TAG, "rgbScore = " + rgbScore);
                    }
                    if(msg.equals("SUCC")) {
                        if(code == 10000) {
                            runOnUiThread(() -> textView1.setText("相机打开成功"));
                            Log.d(TAG, "相机打开成功");
                        } else {
                            String user_id = (String) map.get("return_user_info_id");
                            String name = (String) map.get("return_user_info_name");
                            runOnUiThread(() -> {
                                textView1.setText("识别成功");
                                textView2.setText("用户" + user_id + ", 姓名:" + name);
                            });
                            Log.d(TAG, "verity user_id = " + user_id + ", name = " + name);
                        }
                    } else {
                        runOnUiThread(() -> textView1.setText(msg));
                    }
                }
            });
        });

        findViewById(R.id.stop_verity).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().stopVerify(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    runOnUiThread(() -> textView1.setText("停止识别" + msg));
                    Log.d(TAG, "stop verity msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.get_feature).setOnClickListener((view) -> {
            map.put("pictureURL", "sdcard/123.jpg");
            //Bitmap bitmap = BitmapUtils.getBitmap("sdcard/1.png");
            //byte[] bitmapData = BitmapUtils.bitmapToBytes(bitmap);
            //map.put("bitmapData", bitmapData);
            BaiduFacePay.getInstance().getFaceFeature(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    byte[] feature = (byte[]) map.get("feature");
                    Log.d(TAG, "get feature msg = " + msg + ", code = " + code);
                    Log.d(TAG, "feature = " + Base64.getEncoder().encodeToString(feature));
                }
            });
        });

        findViewById(R.id.del_user).setOnClickListener((view) -> {
            //map.put("userID", "123456789");
            map.put("userName", "liuj");
            BaiduFacePay.getInstance().deleteUser(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    runOnUiThread(() -> textView1.setText("用户liuj删除" + msg));
                    Log.d(TAG, "del user msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.del_all_user).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().deleteAllUser(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    runOnUiThread(() -> textView1.setText("所有用户删除" + msg));
                    Log.d(TAG, "del all user msg = " + msg + ", code = " + code);
                }
            });
        });


        findViewById(R.id.release).setOnClickListener((view) -> {
            QZXTools.logD(TAG +"我开始销毁了");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                  //  BaiduFacePay.getInstance().releaseBaiduFace(MyAPP.getInstance());
                }
            });

            QZXTools.logD(TAG +"我销毁完成了");
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onDestroy() {
        super.onDestroy();
      //  BaiduFacePay.getInstance().releaseBaiduFace(MyAPP.getInstance());
    }
}